import { LOG_TYPE, LOG_TYPE_INDEX, DNI_CODE } from "./enums";
const UA = navigator.userAgent;

window.log = (type, ...text) => {
  if (type == !!type) type += "";
  if (LOG_TYPE_INDEX.indexOf(+type) == -1) {
    text = [type, ...text];
    type = 0;
  }
  console[LOG_TYPE[type]]("[log]:", ...text);
};

export default {
  env: {
    get: function () {
      return process.env.VUE_APP_PEO_ENV || process.env.NODE_ENV;
    },
    isDev: function () {
      return ["development", "dev"].includes(this.get());
    },
    isTest: function () {
      return ["test"].includes(this.get());
    },
    isProd: function () {
      return ["production", "prod"].includes(this.get());
    },
  },
  ua: {
    isWx: () => UA.toLowerCase().match(/MicroMessenger/i) == "micromessenger",
    isAndroid: () => UA.indexOf("Android") > -1 || UA.indexOf("Adr") > -1,
    isIos: () => !!UA.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
  },
  /**
   * 设置浏览器默认配置
   * @param {navbar标题} title
   * @returns
   */
  setTitle: (title) => (document.title = title),
  scroll2bottom: () =>
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: "smooth",
    }),
  isInViewPort: (iv = 90) => {
    let el = document.getElementById("js-bottom");
    let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    let top = el.getBoundingClientRect() && el.getBoundingClientRect().top;
    return top <= viewPortHeight - iv;
  },
  /**
   * hash模式获取参数值
   * @param {要获取的字段} key
   * @returns
   */
  getHashUrlQueryByKey: function (key) {
    let reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`);
    let arr = location.hash.substr(2).split("?");
    let r = arr.length > 1 ? arr[1].match(reg) : null;
    return r != null ? unescape(r[2]) : null;
  },
  getHashUrlQuery: function (obj) {
    for (let key in obj) {
      obj[key] = this.getHashUrlQueryByKey(key);
    }
  },
  /**
   * 获取使用的公众号主体
   * 数据隔离的依据
   * @param {公众号主体} subject
   * @returns
   */
  getSubject: function (subject) {
    return this.getHashUrlQuery("subject") || subject.get() || "mmm";
  },
  /**
   * 对象 --> 拼接字符串
   * @param {query对象} o
   * @returns name=tom&age=1
   */
  setQueryStringParams: function (o, symbol = "&") {
    let temp = {
        ...o,
        _t: +new Date(),
      },
      str = "";
    for (let t in temp) {
      str += t + "=" + temp[t] + symbol;
    }
    return str.substr(0, str.length - 1);
  },
  navigateTo: function (u) {
    window.location = u.path + this.setQueryStringParams(u.params);
  },
  redirectTo: function (u) {
    window.replace(u.path + this.setQueryStringParams(u.params));
  },
  openIframe: function (u) {
    window.open(u);
  },
  insertOrDestroyIframe(url, callback) {
    var iframebox = document.querySelector("#iframe-box");
    // 移除已有的iframe
    document.querySelectorAll("iframe").forEach(function (iframe) {
      iframe.remove();
    });
    var iframe = document.createElement("iframe");
    iframe.style.display = "none"; // 隐藏iframe
    iframebox.appendChild(iframe);

    // 设置iframe的属性
    iframe.src = url;
    iframe.setAttribute('allow', 'microphone *;camera *');
    iframe.style.width = "100%";
    iframe.style.height = "100%";
    iframe.style.display = "block"; // 或者 'inline'、'flex'等
    iframe.onload = function () {
      callback();
    };
  },
  /**
   * 判断数据类型
   * Object.prototype.toString.call(i) === '[object String]'
   * @param {*} i
   * @returns
   */
  isString: (i) => i === i + "",
  isBoolean: (i) => i === !!i,
  /**
   * 字符串脱敏
   * @param {格式化对象} str
   * @param {+正序坐标} start
   * @param {-倒序坐标} end
   * @returns
   */
  formatSensitiveStr: (str, start, end) => {
    let len = str.length;
    let first = str.substr(0, start);
    let last = str.substr(end);
    let middle = str.substring(start, len - Math.abs(end)).replace(/[\s\S]/gi, "*");
    return first + middle + last;
  },
  /**
   * 模拟手机号
   * @returns 150****7209
   */
  createMockPhone: () => {
    let prefixArray = [
      "139",
      "138",
      "137",
      "136",
      "135",
      "134",
      "159",
      "158",
      "157",
      "150",
      "151",
      "152",
      "188",
      "187",
      "182",
      "183",
      "184",
      "178",
      "130",
      "131",
      "132",
      "156",
      "155",
      "186",
      "185",
      "176",
      "133",
      "153",
      "189",
      "180",
      "181",
      "177",
    ];
    let i = parseInt(10 * Math.random());
    let prefix = prefixArray[i];
    for (let j = 0; j < 8; j++) prefix = prefix + Math.floor(Math.random() * 10);
    return prefix.replace(/(\d{3})\d*(\d{4})/, "$1****$2");
  },
  /**
   * 动态加载js
   * @param {*} url -- 资源链接
   * @param {*} cb -- 回调
   * @param {*} isCache -- 缓存标识
   */
  loadJS(url, cb, isCache = false) {
    const script = document.createElement("script");
    const head = document.head;
    script.type = "text/JavaScript";
    if (isCache) {
      script.src = url + "?_t=" + new Date().getTime();
    } else {
      script.src = url;
    }
    if (script.addEventListener) {
      script.addEventListener("load", cb, false);
    }
    head.appendChild(script);
  },
  /**
   * 动态加载css
   * @param {*} url -- 资源链接
   * @param {*} isCache -- 缓存标识
   */
  loadCSS(url, isCache = false) {
    const element = document.createElement("link");
    element.setAttribute("rel", "stylesheet");
    element.setAttribute("type", "text/css");
    if (isCache) {
      element.setAttribute("href", url + "?t=" + new Date().getTime());
    } else {
      element.setAttribute("href", url);
    }
    document.head.appendChild(element);
  },

  validatePhone(phone) {
    var pattern = /^[67]\d{8}$/;
    return pattern.test(phone);
  },
  validateVerifyCode(code) {
    var pattern = /^\d{4}$/;
    return pattern.test(code);
  },
  validateEmail(email) {
    var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    return emailRegex.test(email);
  },
  isAgeLessThan20(birthDate) {
    const today = new Date();
    const birth = new Date(birthDate);
    let age = today.getFullYear() - birth.getFullYear();
    const m = today.getMonth() - birth.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) {
      age--;
    }
    return age < 20;
  },
  isAgeGreaterThan60(birthDate) {
    const today = new Date();
    const birth = new Date(birthDate);
    let age = today.getFullYear() - birth.getFullYear();
    const m = today.getMonth() - birth.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) {
      age--;
    }
    return age > 60;
  },
  validDNI(str) {
    if (!str) return false;
    if (str.length != 9) return false;

    const firstEight = str.substring(0, 8); // 截取前8位
    const lastOne = str.substring(str.length - 1, str.length); // 截取最后1位

    const remainder = firstEight % 23; // 取余数

    return lastOne === DNI_CODE.get(remainder);
  },
};
